package common

import (
	"socket/model/user"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/spf13/viper"
)

//定义加密秘钥，服务器要保存好
var key = []byte(viper.GetString("jwt.secret"))

type Clams struct {
	UserId uint
	jwt.StandardClaims
}

//ReleaseToken 获取token
func ReleaseToken(user user.User) (string, error) {
	//token有效期设置7天 7 * 24 * time.Hour
	expirationTime := time.Now().Add(7 * 24 * time.Hour)
	claims := &Clams{
		UserId: user.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(),
			IssuedAt:  time.Now().Unix(),
			Issuer:    "project",
			Subject:   "user token",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(key)
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

//ParseToken 解析token
func ParseToken(tokenString string) (*jwt.Token, *Clams, error) {
	clams := &Clams{}
	token, err := jwt.ParseWithClaims(tokenString, clams, func(token *jwt.Token) (i interface{}, err error) {
		return key, nil
	})
	return token, clams, err
}
